/**
 * Created by Freeman on 2016/8/12.
 */
import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as Actions from '../../actions'
import Tags from '../Home/Tags'
import Articles from '../Home/Articles'
import LoadMore from '../Home/LoadMore'
class Posts extends Component {
    constructor(props) {
        super(props)
        this.handleChange = this.handleChange.bind(this);
        this.handleRemoveArticle = this.handleRemoveArticle.bind(this);
    }
    componentDidMount(){
        const {actions,tagList,auth} = this.props;
        actions.changeOptions({'userId':auth.user._id,'isEdit':true});
        if(tagList.length < 1){
            actions.getTagList()
        }
        actions.getArticleList(false)

    }
    handleChange(e,option,isAdd=false){
        e.preventDefault()
        const { actions } = this.props
        actions.changeOptions(option)
        actions.getArticleList(isAdd)
    }

    handleLoadMore(e){
        const {options} = this.props;
        let currentPage = options.pageNo;
        this.handleChange(e,{'pageNo':++currentPage},true)
    }

    handleRemoveArticle(e,id){
        e.preventDefault();
        const { actions } = this.props;
        actions.removeArticle(id)
    }

    render() {
        const {articleList,tagList,options} = this.props;
        return (
            <div>
                <Tags tagList={tagList} options={options} isFetching={articleList.isFetching} changeSort={this.handleChange} />
                <Articles articleList={articleList.items} isEdit={options.isEdit} removeArticle={this.handleRemoveArticle} />
                {articleList.isMore && <LoadMore isFetching={articleList.isFetching} addData={this.handleLoadMore} />}
            </div>
        )
    }
}


Posts.propTypes = {
    auth:PropTypes.object.isRequired,
    tagList:PropTypes.array.isRequired,
    articleList:PropTypes.object.isRequired,
    options:PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired
};

const mapStateToProps = state =>{
    return {
        articleList:state.articleList,
        tagList: state.tagList,
        options: state.options,
        auth:state.auth
    }
};

const mapDispatchToProps = dispatch =>{
    return {
        actions: bindActionCreators(Actions, dispatch)
    }
};
Posts = connect(
    mapStateToProps,
    mapDispatchToProps
)(Posts);


export default Posts